<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :status-icon="true" 
        >
          <el-form-item
            v-if="user.level != 3"
            label="所属村"
            prop="villageWrap"
          >
            <el-cascader
              v-model="ruleForm.villageWrap"
              :options="villageCascader"
              :props="villageProp"
              placeholder="请选择所属村"
              clearable
              @change="change"
            />
          </el-form-item>
          <el-form-item
            label="所属组"
            prop="group"
          >
            <el-select
              v-model.number="ruleForm.group"
              placeholder="请选择所属组"
              clearable
            >
              <el-option
                v-for="item in groupAtt"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="姓名"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入村民姓名"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="性别"
            prop="sex"
          >
            <el-select
              v-model.number="ruleForm.sex"
              placeholder="请选择性别"
              clearable
            >
              <el-option
                label="男"
                :value="0"
              />
              <el-option
                label="女"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="民族"
            prop="nation"
          >
            <el-select
              v-model.number="ruleForm.nation"
              placeholder="请选择所属民族"
              clearable
              @clear="ruleForm.nation = null"
            >
              <el-option
                v-for="(item, index) in nationAtt"
                :key="index"
                :label="item"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="电话"
            prop="phone"
          >
            <el-input
              v-model="ruleForm.phone"
              placeholder="请输入村民手机号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="身份证号"
            prop="identityNumber"
          >
            <el-input
              v-model="ruleForm.identityNumber"
              placeholder="请输入村民身份证号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="家庭地址"
            prop="address"
          >
            <el-input
              v-model="ruleForm.address"
              placeholder="请输入村民家庭地址"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="账号"
            prop="account"
          >
            <el-input
              v-model="ruleForm.account"
              placeholder="请输入村民账号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="用户密码"
            prop="password"
          >
            <el-input
              v-model="ruleForm.password"
              type="password"
              auto-complete="off"
              :placeholder="id ? '不填则默认原来密码': '请填写密码'"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? "立即创建" : "保存编辑" }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "Form",
  props: {
    id: {},
    pageNo: {},
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  data() {
    return {
      ruleForm: {
        villageWrap: [],
        village: [],
        group: "",
        name: "",
        sex: 0,
        nation: 1,
        phone: "",
        identityNumber: "",
        politicalStatus: 0,
        address: "",
        status: 0,
        account: "",
        password: "123456",
      },
      rules: {
        villageWrap: [
          { required: true, message: "请选择所属村", trigger: "change" }
        ],
        group: [
          { required: true, message: "请选择所属组", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入村民姓名", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        nation: [
          { required: false, message: "请选择所属民族", trigger: "change" }
        ],
        phone: [
          { required: false, message: "请输入村民手机号", trigger: "blur" }
        ],
        identityNumber: [
          { required: false, message: "请输入村民身份证号", trigger: "blur" }
        ],
        address: [
          { required: false, message: "请输入村民家庭地址", trigger: "blur" }
        ],
        account: [
          { required: true, message: "请输入村民账号", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入账号密码", trigger: "blur" }
        ],
      },
      nationAtt: [
        "汉族",
        "蒙古族",
        "回族",
        "藏族",
        "维吾尔族",
        "苗族",
        "彝族",
        "壮族",
        "布依族",
        "朝鲜族",
        "满族",
        "侗族",
        "瑶族",
        "白族",
        "土家族",
        "哈尼族",
        "哈萨克族",
        "傣族",
        "黎族",
        "傈僳族",
        "佤族",
        "畲族",
        "高山族",
        "拉祜族",
        "水族",
        "东乡族",
        "纳西族",
        "景颇族",
        "柯尔克孜族",
        "土族",
        "达斡尔族",
        "仫佬族",
        "羌族",
        "布朗族",
        "撒拉族",
        "毛南族",
        "仡佬族",
        "锡伯族",
        "阿昌族",
        "普米族",
        "塔吉克族",
        "怒族",
        "乌孜别克族",
        "俄罗斯族",
        "鄂温克族",
        "德昂族",
        "保安族",
        "裕固族",
        "京族",
        "塔塔尔族",
        "独龙族",
        "鄂伦春族",
        "赫哲族",
        "门巴族",
        "珞巴族",
        "基诺族",
      ],
      options: [],
      dialogImageUrl: "",
      dialogVisible: false,
      // fileList: [],
      createForm: {},
      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      groupAtt: [],
      sexAtt: [{ sex: "男", value: 0 },{ sex: "女", value: 1 }],
    };
  },
  async created() {
    await this.init();
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/villager`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "Villager" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(`/villager/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "Villager", props: { pageNo: this.pageNo } });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`villager/${id}?join=village&join=group&join=village.town`);

      this.groupAtt = res.data.village.group

      const town = await this.$http.get(`town/${res.data.village.town.id}?join=area`);
      res.data.villageWrap = [town.data.area.id, res.data.village.town.id, res.data.village.id];

      this.change(res.data.villageWrap)

      res.data.village = res.data.village.id
      res.data.group = res.data.group && res.data.group.id

      this.ruleForm = Object.assign({}, res.data);

      // this.resetForm.villageWrap = res.data.villageWrap
      this.rules['password'] = [
          { required: false, message: "请输入账号密码", trigger: "blur" }
        ]
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.ruleForm.village = val[val.length - 1]
      this.ruleForm.group = ""
      const res = await this.$http.get(`village/${this.ruleForm.village}?join=group`)
      this.groupAtt = res.data.group
    },
    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 3) {
          //村级
        this.change([this.user.village.id])
      } 
    },
  },
};
</script>
